package com.vanzo.some.test;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;

/**
 * Created by tisen on 2017/10/24.
 */

public class UserSerialiser implements JsonSerializer<User> {
    @Override
    public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("姓名", src.getName());
        jsonObject.addProperty("年龄", src.getAge());
        jsonObject.addProperty("性别", src.getSex());

        final JsonArray jsonFriendArray = new JsonArray();
        if (src.getFriends() != null) {
            for (String friend : src.getFriends()) {
                final JsonPrimitive jsonFriend = new JsonPrimitive(friend);
                jsonFriendArray.add(jsonFriend);
            }
            jsonObject.add("朋友", jsonFriendArray);
        }

        return jsonObject;
    }
}
